package com.douyin.dto;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 渲染数据DTO - 对应参考项目的RenderData结构
 */
@Data
public class RenderDataDto {

    private List<ItemInfo> itemList;

    /**
     * 获取第一个视频项目信息
     */
    public ItemInfo getItemInfo() {
        if (itemList == null || itemList.isEmpty()) {
            return new ItemInfo();
        }
        return itemList.get(0);
    }

    /**
     * 获取视频ID和下载URL - 参考项目的getVideoId方法
     */
    public String getVideoDownloadUrl() {
        JSONObject video = this.getItemInfo().getVideo();
        if (video == null) {
            return null;
        }

        JSONObject playAddr = video.getJSONObject("play_addr");
        if (playAddr == null) {
            return null;
        }

        String videoId = playAddr.getStr("uri");
        if (videoId == null || videoId.trim().isEmpty()) {
            return null;
        }
        
        // 使用参考项目的URL格式
        return String.format("https://aweme.snssdk.com/aweme/v1/play/?video_id=%s&ratio=1080p&line=0", videoId);
    }

    /**
     * 获取所有可能的下载URL
     */
    public List<String> getAllDownloadUrls() {
        List<String> urls = new ArrayList<>();
        
        try {
            JSONObject video = this.getItemInfo().getVideo();
            if (video == null) {
                return urls;
            }

            JSONObject playAddr = video.getJSONObject("play_addr");
            if (playAddr == null) {
                return urls;
            }

            String videoId = playAddr.getStr("uri");
            if (videoId != null && !videoId.trim().isEmpty()) {
                // 添加多种分辨率的下载链接
                urls.add(String.format("https://aweme.snssdk.com/aweme/v1/play/?video_id=%s&ratio=1080p&line=0", videoId));
                urls.add(String.format("https://aweme.snssdk.com/aweme/v1/play/?video_id=%s&ratio=720p&line=0", videoId));
                urls.add(String.format("https://aweme.snssdk.com/aweme/v1/play/?video_id=%s&ratio=540p&line=0", videoId));
                
                // 无水印版本
                urls.add(String.format("https://aweme.snssdk.com/aweme/v1/play/?video_id=%s&ratio=720p&line=0&watermark=0", videoId));
            }

            // 如果有直接的播放地址，也添加进去
            if (playAddr.containsKey("url_list")) {
                JSONArray urlList = playAddr.getJSONArray("url_list");
                if (urlList != null && !urlList.isEmpty()) {
                    for (int i = 0; i < urlList.size(); i++) {
                        String url = urlList.getStr(i);
                        if (url != null && !url.trim().isEmpty()) {
                            // 转换为无水印版本
                            String noWatermarkUrl = url.replace("playwm", "play")
                                                      .replace("watermark=1", "watermark=0");
                            urls.add(noWatermarkUrl);
                        }
                    }
                }
            }
            
        } catch (Exception e) {
            // 忽略异常，返回已收集的URL
        }
        
        return urls;
    }

    /**
     * 获取图片列表 - 参考项目的getImages方法
     */
    public List<String> getImages() {
        List<String> list = new ArrayList<>();
        ItemInfo itemInfo = this.getItemInfo();
        
        if (itemInfo.getImages() == null || itemInfo.getImages().isEmpty()) {
            return list;
        }

        try {
            JSONArray images = itemInfo.getImages()
                    .getJSONObject(itemInfo.getImages().size() - 1)
                    .getJSONArray("images");
            
            int size = images.size();
            for (int i = 0; i < size; i++) {
                JSONObject image = images.getJSONObject(i);
                if (image.containsKey("url_list")) {
                    JSONArray imgUrls = image.getJSONArray("url_list");
                    if (imgUrls != null && !imgUrls.isEmpty()) {
                        String imageUrl = imgUrls.getStr(imgUrls.size() - 1);
                        if (imageUrl != null && !imageUrl.trim().isEmpty()) {
                            list.add(imageUrl);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 忽略异常，返回空列表
        }
        
        return list;
    }

    /**
     * 项目信息内部类
     */
    @Data
    public static class ItemInfo {
        private String desc;
        private JSONObject author;
        private JSONObject video;
        private JSONArray images;
        private String awemeId;
        
        /**
         * 获取作者昵称
         */
        public String getAuthorNickname() {
            if (author != null && author.containsKey("nickname")) {
                return author.getStr("nickname");
            }
            return "";
        }
        
        /**
         * 获取视频时长（秒）
         */
        public int getDuration() {
            if (video != null && video.containsKey("duration")) {
                return video.getInt("duration", 0) / 1000;
            }
            return 0;
        }
        
        /**
         * 获取封面图URL
         */
        public String getCoverUrl() {
            if (video != null && video.containsKey("origin_cover")) {
                JSONObject cover = video.getJSONObject("origin_cover");
                if (cover != null && cover.containsKey("url_list")) {
                    JSONArray urlList = cover.getJSONArray("url_list");
                    if (urlList != null && !urlList.isEmpty()) {
                        return urlList.getStr(0);
                    }
                }
            }
            return "";
        }
        
        /**
         * 是否为图集
         */
        public boolean isImageSet() {
            return images != null && !images.isEmpty();
        }
    }
}